package com.yxcz.interceptor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Stack;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yxcz.model.Menu;
import com.yxcz.model.User;
import com.yxcz.service.LoginService;
import com.yxcz.service.MenuService;

public class CheckLoginInterceptor extends HandlerInterceptorAdapter {

	private Logger log = Logger.getLogger(CheckLoginInterceptor.class);

	@Resource
	private LoginService loginService;
	@Resource
	private MenuService menuService;

	private static final String[] IGNORE_URI = { "user/login", "user/doLogin" };

	/**
	 * 前置验证用户是否登陆
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub

		boolean flag = false;
		String url = request.getRequestURL().toString();

		log.info(url);
		System.out.println(">>>: " + url);
		for (String s : IGNORE_URI) {
			if (url.contains(s)) {
				flag = true;
				break;
			}
		}
		if (!flag) {
			if (request.getSession().getAttribute("accountName") == null) {
				if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){ //如果是ajax请求响应头会有，x-requested-with  
					
					response.setHeader("sessionstatus", "timeout");return false;
	            }
				response.sendRedirect(request.getContextPath() + "/user/login");
				return false;
			}
		}

		return super.preHandle(request, response, handler);
	}

	/**
	 * 后置加载用户信息
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

		if (request.getSession().getAttribute("accountName") != null && modelAndView != null) {
			//查用户信息
			User user = loginService.getUserInfo(request.getSession().getAttribute("accountName").toString());
			modelAndView.addObject("user", user);
			
			//查菜单树
			ArrayList<Menu> menutree = menuService.getMenuTree(user.getId());
			modelAndView.addObject("menutree",menutree);
			
			//查路由
			Stack<Menu> temprouters = menuService.getRouter(request.getServletPath());
			ArrayList<Menu> routers= new ArrayList<>();
			
			while(!temprouters.isEmpty())
			{
				routers.add(temprouters.pop());
			}
		
			modelAndView.addObject("routers",routers);
		}

		super.postHandle(request, response, handler, modelAndView);
	}

}
